using JetBrains.Annotations;
using Orchard.Alias;
using Orchard.ContentManagement.Handlers;
using Orchard.Data;
using Mod.DisplayTypes.Models;
using System.Web;
using Orchard.Tokens;
using Mod.DisplayTypes.Settings;
using System.Collections.Generic;
using Orchard;
using System;
using Orchard.Localization;
using Orchard.UI.Notify;

namespace Mod.DisplayTypes.Handlers
{
    [UsedImplicitly]
	
    public class DisplayTypePartHandler : ContentHandler
    {
        private readonly IAliasService aliasService;
        private readonly ITokenizer tokenizer;
        private readonly IOrchardServices services;

        public DisplayTypePartHandler(IRepository<DisplayTypePartRecord> repository, IAliasService aliasService, ITokenizer tokenizer, 
            IOrchardServices services)
        {
            Filters.Add(StorageFilter.For(repository));
            this.aliasService = aliasService;
            this.tokenizer = tokenizer;
            this.services = services;
            T = NullLocalizer.Instance;

            OnPublished<DisplayTypePart>((ctx, part) => PublishAlias(part));

            OnGetContentItemMetadata<DisplayTypePart>((ctx, part) =>
            {
                //if (part. != null)
                //ctx.Metadata.DisplayRouteValues.Add("player", "Contents/Player/Display/Item/" + part.Id);
            });
        }

        public Localizer T { get; set; }

        private void PublishAlias(DisplayTypePart part)
        {
            var typeSettings = part.Settings.GetModel<DisplayTypePartTypePartSettings>();
            var id = part.Id;

            var routes = typeSettings.RouteList;
            try
            {
                foreach (var r in routes)
                {
                    var routePath = String.Format("Contents/{0}/Display/Item/{1}", r.DisplayType, id);

                    var path = r.Slugs;
                    var tPath = tokenizer.Replace(path, new Dictionary<string, object> { { "Content", part.ContentItem } }, new ReplaceOptions { Encoding = ReplaceOptions.NoEncode });
                    tPath = tPath.TrimStart('/', '\\');

                    aliasService.Set(tPath, routePath, "Custom");
                }


            }
            catch (Exception ex)
            {
                services.Notifier.Error(T("An error occured while creating a display type alias. '{0}'. Please check the values are correct.", ex.Message));
            }
        }


        //private string GetExistingPathForAlias(string aliasPath)
        //{
        //    var routeValues = aliasService.Get(aliasPath.TrimStart('/', '\\'));
        //    if (routeValues == null) return null;

        //    return aliasService.LookupVirtualPaths(routeValues, HttpContext)
        //        .Select(vpd => vpd.VirtualPath)
        //        .FirstOrDefault();
        //}
    }
}
